﻿using System.IO;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
using UnityEngine.U2D;

namespace zframe.editor
{
    public class AutoCreateSpriteAtlas
    {
        [MenuItem("Assets/zframe/生成图集")]
        static void CreateAtlas()
        {
            string relativePath = AssetFileUtils.GetSelectFolder();
            string[] files = FileUtils.GetFilesByExts(relativePath, new string[] { ".png", ".jpg" });
            if (files.Length > 0)
            {
                Sprite[] sprites = new Sprite[files.Length];
                for (int i = 0; i < files.Length; i++)
                {
                    var sp = AssetDatabase.LoadAssetAtPath<Sprite>(files[i]);
                    sprites.SetValue(sp, i);
                }
                SpriteAtlas atlas = GenSpriteAtlas();
                atlas.Add(sprites);
                string folder = FileUtils.GetDirLastFolderName(relativePath);

                string relaPath = Path.Combine("Assets", "spriteAtlas", folder + "_atlas.spriteAtlas");
                AssetDatabase.CreateAsset(atlas, relaPath);//只能传入相对路径
                AssetDatabase.Refresh();
                string msg = $"图集已生成到 {relaPath}";
                Debug.Log(msg);
                EditorUtility.DisplayDialog("完成提示", msg, "确定", "取消");

            }
            else
            {
                EditorUtility.DisplayDialog("提示", "没有可生成的图片", "确定", "取消");
            }

        }
        static SpriteAtlas GenSpriteAtlas()
        {
            SpriteAtlas atlas = new SpriteAtlas();
            SpriteAtlasPackingSettings pack = new SpriteAtlasPackingSettings();
            pack.enableTightPacking = true; //紧密打包意味着精灵的网格在打包时用作精灵的边界，而不是整个矩形。 
            atlas.SetPackingSettings(pack);
            SpriteAtlasTextureSettings src = new SpriteAtlasTextureSettings();
            src.filterMode = FilterMode.Bilinear;
            src.anisoLevel = 1;
            src.generateMipMaps = false;
            atlas.SetTextureSettings(src);
            return atlas;
        }

    }
}
